import cgi
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.ext.webapp import template
import appengine_admin

from models import *


#return one user and all info
class UserInfo(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""
	<id>%s</id>
	<email>%s</email>
	<username>%s</username>
	<firstname>%s</firstname>
	<lastname>%s</lastname>
	<currentzip>%s</currentzip>
	<gender>%s</gender>
	<birthday>%s</birthday>
	<password>%s</password>
	<is_active>%s</is_active>
	<is_public>%s</is_public>
	<image><img src='/img?img_id=%s'></img></image>
""" % (user.key().id(), user.email, user.username,  user.firstname, user.lastname, user.currentzip, user.gender, user.birthday, user.password, user.is_active, user.is_public, user.key() )
	)
	if (user.user_associations).count() != 0:
            self.response.out.write("	<associations>")
            for association in user.user_associations:	    
                self.response.out.write(
"""
	    <association>
		<associationtype>%s</associationtype>
		<associationid>%s</associationid>
	    </association>
""" % (association.associationtype, association.associationid)
        	)

            self.response.out.write("	</associations>")
	if (user.user_locations).count() != 0:
  	    self.response.out.write("	<savedlocations>")
            for location in user.user_locations:
	    	    self.response.out.write(
"""
	    <location>
		<city>%s</city>
		<state>%s</state>
		<zip>%s</zip>
	    </location>
""" % (location.city, location.state, location.zipcode)
		)
            self.response.out.write("	</savedlocations>")
        self.response.out.write("</account>")


#list of users full information
class UsersList(webapp.RequestHandler):
    def get(self):
        users= Gauser.all()
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<users>
"""
	)
	for user in users:
	    self.response.out.write("	    <account>")
            self.response.out.write(
"""
		<id>%s</id>
		<email>%s</email>
		<firstname>%s</firstname>
		<lastname>%s</lastname>
		<currentzip>%s</currentzip>
		<gender>%s</gender>
		<birthday>%s</birthday>
		<password>%s</password>
		<is_active>%s</is_active>
		<is_public>%s</is_public>
		<image><img src='/img?img_id=%s'></img></image>
""" % (user.key().id(), user.email, user.firstname, user.lastname, user.currentzip, user.gender, user.birthday, user.password, user.is_active, user.is_public, user.key() )
	    )
	    if (user.user_associations).count() != 0:
                self.response.out.write("		<associations>")
                for association in user.user_associations:	    
                    self.response.out.write(
"""
	   	    <association>
		        <associationtype>%s</associationtype>
		        <associationid>%s</associationid>
	            </association>
""" % (association.associationtype, association.associationid)
        	    )

                self.response.out.write("		</associations>")
	    if (user.user_locations).count() != 0:
  	       self.response.out.write(
"""	   	
		<savedlocations>"""
	       )
               for location in user.user_locations:
	           self.response.out.write(
"""
	    	    <location>
		        <city>%s</city>
		        <state>%s</state>
		        <zip>%s</zip>
	   	    </location>
""" % (location.city, location.state, location.zipcode)
	           )
  	       self.response.out.write("	   	</savedlocations>")
	    self.response.out.write(
"""	    
	    </account>
"""
	    )     
        self.response.out.write("</users>")


#return one user lite version
class UserLiteInfo(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""
	<id>%s</id>
	<email>%s</email>
	<firstname>%s</firstname>
	<lastname>%s</lastname>
	<is_active>%s</is_active>
	<image><img src='/img?img_id=%s'></img></image>
""" % (user.key().id(), user.email, user.firstname, user.lastname, user.is_active, user.key())
	)
        self.response.out.write("</account>")


#return the saved locations of one user
class UserSavedLocations(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""
	<id>%s</id>
""" % user.key().id()
	)
        if (user.user_locations).count() != 0:
	    self.response.out.write(
"""	    <savedlocations>
"""
	)
            for location in user.user_locations:
		    self.response.out.write(
"""	        <location>
		    <city>%s</city>
		    <state>%s</state>
		    <zip>%s</zip>
	        </location>
""" % (location.city, location.state, location.zipcode)
        	    )
            self.response.out.write("	    </savedlocations>")
        self.response.out.write(
"""
</account>
"""	)


#friends of users
class UserFriends(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""
	<id>%s</id>
""" % user.key().id()
	)
        if (user.user_friends).count() != 0:
	    self.response.out.write(
"""	    <friendships>
"""
	)
            for buddy in user.user_friends:
		    self.response.out.write(
"""	        <friend><id>%s</id></friend>
""" % (buddy.friend.key().id(),)
        	    )
            self.response.out.write("	    </friendships>")
        self.response.out.write(
"""
</account>
"""	)

#favorited businesses of users
class UserFavoriteBusinesses(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""
	<id>%s</id>
""" % user.key().id()
	)
        if (user.user_businesses).count() != 0:
	    self.response.out.write(
"""	    <fav_businesses>
"""
	)
            for biz in user.user_businesses:
		    self.response.out.write(
"""	        <business><id>%s</id></business>
""" % (biz.gabusiness.key().id(),)
        	    )
            self.response.out.write("	    </fav_businesses>")
        self.response.out.write(
"""
</account>
"""	)


#full business info
class BusinessInfo(webapp.RequestHandler):
    def get(self, ID):
        biz= Gabusiness.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<account>"""
	)
        self.response.out.write(
"""    
	<id>%s</id>
	<bizname>%s</bizname>
	<businesstype>%s</businesstype>
	<contactemail>%s</contactemail>
	<contactname>%s</contactname>
	<url>%s</url>
	<ein>%s</ein>
	<supportemail>%s</supportemail>
	<phone>%s</phone>
	<fax>%s</fax>
	<is_active>%s</is_active>
	""" % (biz.key().id(), biz.bizname,  biz.biztype , biz.contactemail, biz.contactname, biz.url, biz.ein, biz.supportemail, biz.phonenumber, biz.faxnumber, biz.is_active)
	)
	#all businesses should have one location so these checks might not be needed
	if (biz.business_locations).count() != 0:
            self.response.out.write("<location>")
            for bizlocation in biz.business_locations:
	        self.response.out.write(
"""
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (bizlocation.address_1, bizlocation.city, bizlocation.state, bizlocation.zipcode)
				    )
	        self.response.out.write("	</location>")
        self.response.out.write(
"""
</account>"""
	)

#full business info lite version
class BusinessLiteInfo(webapp.RequestHandler):
    def get(self, ID):
        biz= Gabusiness.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	)
        self.response.out.write(
"""    
	<id>%s</id>
	<bizname>%s</bizname>
	<is_active>%s</is_active>
	""" % (biz.key().id(), biz.bizname, biz.is_active)
	)
	#all businesses should have one location so these checks might not be needed
	if (biz.business_locations).count() != 0:
            self.response.out.write("<location>")
            for bizlocation in biz.business_locations:
	        self.response.out.write(
"""
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (bizlocation.address_1, bizlocation.city, bizlocation.state, bizlocation.zipcode)
				    )
	        self.response.out.write("	</location>")
        self.response.out.write(
"""
</businessaccount>"""
	)


#list of businesses
class BusinessesList(webapp.RequestHandler):
    def get(self):
        bizs= Gabusiness.all()
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businesses>
"""
	)
	for biz in bizs:
	    self.response.out.write("	    <account>")
            self.response.out.write(
"""    
		<id>%s</id>
		<bizname>%s</bizname>
		<businesstype>%s</businesstype>
		<contactemail>%s</contactemail>
		<contactname>%s</contactname>
		<url>%s</url>
		<ein>%s</ein>
		<supportemail>%s</supportemail>
		<phone>%s</phone>
		<fax>%s</fax>
		<is_active>%s</is_active>
""" % (biz.key().id(), biz.bizname,  biz.biztype , biz.contactemail, biz.contactname, biz.url, biz.ein, biz.supportemail, biz.phonenumber, biz.faxnumber, biz.is_active)
	)
	    if (biz.business_locations).count() != 0:
                self.response.out.write("		<location>")
                for bizlocation in biz.business_locations:
	            self.response.out.write(
"""			
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (bizlocation.address_1, bizlocation.city, bizlocation.state, bizlocation.zipcode)
		    )
		self.response.out.write("		</location>")
	    self.response.out.write(
"""	    
	    </account>
"""
	    )     
        self.response.out.write("</businesses>")

#location of an event given businessid
class BusinessLocation(webapp.RequestHandler):
    def get(self, ID):
        biz = Gabusiness.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	)
        self.response.out.write(
"""    
	<id>%s</id>
""" % biz.key().id()
	)
	#all businesses should have one location so these checks might not be needed
	if (biz.business_locations).count() != 0:
            self.response.out.write(	"<location>")
            for bizlocation in biz.business_locations:
	        self.response.out.write(
"""
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (bizlocation.address_1, bizlocation.city, bizlocation.state, bizlocation.zipcode)
				    )
	        self.response.out.write("	</location>")
        self.response.out.write(
"""
</businessaccount>"""
	)

#full event info
class EventInfo(webapp.RequestHandler):
    def get(self, ID):
        event= Gaevent.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	)
        self.response.out.write(
"""    
	<id>%s</id>
	<name>%s</name>
	<description>%s</description>
	<tickets>%s</tickets>
	<supportemail>%s</supportemail>
	<supportphone>%s</supportphone>
	<event_start_date>%s</event_start_date>
	<event_end_date>%s</event_end_date>
	<event_start_time>%s</event_start_time>
	<event_end_time>%s</event_end_time>
	<event_expiration>%s</event_expiration>
	<is_featured>%s</is_featured>
	<price>%s</price>
	<likecount>%s</likecount>
	<date_updated>%s</date_updated>
	<date_created>%s</date_created>
	<external_id>%s</external_id>
	<status>%s</status>
	<bid>%s</bid>
	""" % (event.key().id(), event.eventname,  event.eventdescription , event.tickets, event.supportemail, event.supportphone, event.eventstartdate, event.eventenddate, event.eventstarttime, event.eventendtime, event.eventexpiration, event.is_featured, event.price, event.likecount, event.date_updated, event.date_created, event.external_event_id, event.is_active, event.gabusiness.key().id() )
	)
	#all businesses should have one location so these checks might not be needed
	if (event.event_locations).count() != 0:
            self.response.out.write("<location>")
            for eventlocation in event.event_locations:
	        self.response.out.write(
"""
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (eventlocation.address_1, eventlocation.city, eventlocation.state, eventlocation.zipcode)
				    )
	        self.response.out.write("	</location>")
        self.response.out.write(
"""
</event>"""
	)

#get event location given id
class EventLocation(webapp.RequestHandler):
    def get(self, ID):
        event= Gaevent.get_by_id(int(ID))
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<event>"""
	)
        self.response.out.write(
"""    
	<id>%s</id>
	""" % event.key().id()
	)
	#all businesses should have one location so these checks might not be needed
	if (event.event_locations).count() != 0:
            self.response.out.write("<location>")
            for eventlocation in event.event_locations:
	        self.response.out.write(
"""
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
""" % (eventlocation.address_1, eventlocation.city, eventlocation.state, eventlocation.zipcode)
				    )
	        self.response.out.write("	</location>")
        self.response.out.write(
"""
</event>"""
	)
#Image class page
class ImagePage (webapp.RequestHandler):
    def get(self):
        user = db.get(self.request.get("img_id"))
        if user.image:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(user.image)
        else:
            self.response.out.write("No image")

application = webapp.WSGIApplication([
    (r'^/img', ImagePage),
    (r'^/rest/v1/user/id/(.*)/?$', UserInfo ),
    (r'^/rest/v1/user/liteuser/id/(.*)/?$', UserLiteInfo),   
    (r'^/rest/v1/user/savedlocations/id/(.*)/?$', UserSavedLocations),
    (r'^/rest/v1/user/friends/id/(.*)/?$', UserFriends),
    (r'^/rest/v1/user/favoritebusinesses/id/(.*)/?$', UserFavoriteBusinesses),
    (r'^/rest/v1/user/list/?$', UsersList),
    (r'^/rest/v1/business/id/(.*)/?$', BusinessInfo ),
    (r'^/rest/v1/business/litebusiness/id/(.*)/?$', BusinessLiteInfo ),
    (r'^/rest/v1/business/location/id/(.*)/?$', BusinessLocation),
    (r'^/rest/v1/business/list/?$', BusinessesList),
    (r'^/rest/v1/event/id/(.*)/?$', EventInfo ),
    (r'^/rest/v1/event/location/id/(.*)/?$', EventLocation),

], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
